package com.ityu.service.impl;

import com.ityu.exception.InsertSameException;
import com.ityu.exception.UnableDeleteException;
import com.ityu.mapper.DeptMapper;
import com.ityu.pojo.Dept;
import com.ityu.pojo.result.Result;
import com.ityu.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    DeptMapper deptMapper;

    @Override
    public List<Dept> listDept() {
        log.info("-----DeptService-----查询所有部门");
        System.out.println(deptMapper.listDept());
        return deptMapper.listDept();
    }

    @Override
    public void addDept(Dept dept) {
        log.info("-----DeptService-----添加部门,参数为{}",dept);
        dept.setCreateTime(java.time.LocalDateTime.now());
        dept.setUpdateTime(java.time.LocalDateTime.now());
        try {
            deptMapper.addDept(dept);
        } catch (DuplicateKeyException e) {
            log.error("插入重复部门名称{}" ,dept.getName());
            throw new InsertSameException("插入数据不合法或重复，请重试！");
        }
    }

    @Override
    public void deleteDept(Integer id) {
        log.info("-----DeptService-----删除部门,参数为{}", id);
        System.out.println(deptMapper.countDept(id));
        if (deptMapper.countDept(id) == 0){
            deptMapper.deleteDept(id);
        } else {
            log.error("删除仍有员工的部门{}", id);
            throw new UnableDeleteException("删除部门失败，该部门下有员工");
        }
    }

    @Override
    public Object getDeptById(Integer id) {
        log.info("-----DeptService-----根据id查询部门，参数为{}",id);
        return deptMapper.getDeptById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        log.info("-----DeptService-----更新部门,参数为{}",dept);
        dept.setUpdateTime(java.time.LocalDateTime.now());
        try {
            deptMapper.updateDept(dept);
        } catch (DuplicateKeyException e) {
            log.error("修改重复部门名称{}" ,dept.getName());
            throw new InsertSameException("插入数据不合法或重复，请重试！");
        }
    }

}
